package server;

import java.util.*;
import utils.*;

public class TopoDestroyer extends TimerTask {

	int probaDest;

	int probaRestore;

	LinkedList<StringCouple> removedLinksTable;

	public TopoDestroyer(int probaDest, int probaRestore) {
		if (probaDest > 100 || probaDest < 0) {
			System.err.println("Invalid destruction probability");
			System.exit(0);
		} else {
			this.probaDest = probaDest;
		}
		if (probaRestore > 100 || probaRestore < 0) {
			System.err.println("Invalid restore probability");
			System.exit(0);
		} else if (probaRestore < probaDest) {
			System.err
					.println("Invalid restore probability: will lead to empty graph.");
			System.exit(0);
		} else {
			this.probaRestore = probaRestore;
			removedLinksTable = new LinkedList<StringCouple>();
		}
	}

	public void run() {
		Random ran = new Random();
		if (ran.nextInt(100) <= probaDest) {
			// Remove a random link and store it into the removedLinksTable
			Set<String> set = Main.c.neighbour_table.keySet();
			if (set.size() > 0) {
				int index1 = ran.nextInt(set.size());
				int i = 0;
				String selection1 = "";
				for (String s : set) {
					if (i == index1) {
						selection1 = s;
					}
					i++;
				}
				i = 0;
				List<String> toChooseFrom = Main.c.neighbour_table
						.get(selection1);
				if (toChooseFrom.size() > 0) {
					int index2 = ran.nextInt(toChooseFrom.size());
					String selection2 = "";
					for (String s : toChooseFrom) {
						if (i == index2) {
							selection2 = s;
						}
						i++;
					}
					if (!selection1.equals(selection2)) {
						Main.c.delRoute(selection1, selection2);
						removedLinksTable.add(new StringCouple(selection1,
								selection2));
						System.out.println("Random Removal of " + selection1
								+ " " + selection2);
						try {
							Thread.sleep(10000);
						} catch (InterruptedException ex) {

						}
					}
				}
			}
		}
		if (ran.nextInt(100) <= probaRestore) {
			// Take a link from the removedLinksTable and reinstate it.
			if (removedLinksTable.size() > 0) {
				int index = ran.nextInt(removedLinksTable.size());
				int i = 0;
				StringCouple selection = null;
				for (StringCouple s : removedLinksTable) {
					if (i == index) {
						selection = s;
					}
					i++;
				}
				Main.c.addRoute(selection.from, selection.to);
				System.out.println("Random Restoration of " + selection.from
						+ " " + selection.to);
				removedLinksTable.remove(index);
				try {
					Thread.sleep(10000);
				} catch (InterruptedException ex) {

				}
			}
		}
	}

}
